local skynet = require "skynet"
local BanDB = require "modules.ban.BanDB"
local BanConst = require "modules.ban.BanConst"
local TimeUtil = require "core.TimeUtil"

local M = {}

-- 玩家禁用名单 {playerId => {playerId = string, endTime = int, reason = int, desc = string}}
local playerBanList = {}

-- ip封禁名单 {ip => {ip = string, endTime = int, reason = int, desc = string}}
local ipBanList = {}

-- 封禁账号
function M.banPlayer(playerId, endTime, reason, desc)
    if endTime <= TimeUtil.now() then
        return false
    end

    playerBanList[playerId] = {
        playerId = playerId,
        endTime = endTime,
        reason = reason,
        desc = desc
    }

    BanDB.banPlayer(playerId, endTime, reason, desc)
    return true
end

function M.unbanPlayer(playerId)
    playerBanList[playerId] = nil
    BanDB.unbanPlayer(playerId)
end

-- 玩家是否仍然被封禁
function M.playerBanned(playerId)
    local playerBan = playerBanList[playerId]
    return playerBan and playerBan.endTime > TimeUtil.now()
end

function M.banIP(ip, endTime, reason, desc)
    if endTime <= TimeUtil.now() then
        return false
    end

    playerBanList[ip] = {
        ip = ip,
        endTime = endTime,
        reason = reason,
        desc = desc
    }

    BanDB.banIP(ip, endTime, reason)
    return true
end

function M.unbanIP(ip)
    playerBanList[ip] = nil
    BanDB.unbanIP(ip)
end

-- ip 是否仍然被封禁
function M.ipBanned(ip)
    local ipBan = ipBanList[ip]
    return ipBan and ipBan.endTime > TimeUtil.now()
end

function M.ipBannedTime(ip)
    local ipBan = ipBanList[ip]
    if not ipBan or ipBan.endTime <= TimeUtil.now() then
        return
    end

    return ipBan.endTime
end

function M.hasBanning(ip, playerId)
    return M.playerBanned(playerId) or M.ipBanned(ip)
end

function M.start()
end

function M.init()
    skynet.dispatch_lua_queue(M)

    local tempPlayerList = BanDB.getPlayerBanList()
    for i = 1, #playerBanList do
        local banInfo = tempPlayerList[i]
        if banInfo.endTime > TimeUtil.now() then
            playerBanList[banInfo.playerId] = banInfo
        end
    end
    BanDB.resetPlayerBanList(table.values(playerBanList))

    local tempIPList = BanDB.getIpBanList()
    for i = 1, #tempIPList do
        local banInfo = tempIPList[i]
        if banInfo.endTime > TimeUtil.now() then
            ipBanList[banInfo.ip] = banInfo
        end
    end
    BanDB.resetIpBanList(table.values(ipBanList))
end

return M
